import * as echarts from './../../ec-canvas/echarts';
import store from '../../utils/store';
import { studentStateLastApi } from '../../api/trainingData';

Component({
  properties: {
    trainDate: { type: String, value: '' },
    chartHeight: { type: Number, value: 0 },
    chartWidth: { type: Number, value: 0 },
    hideCanvas: { type: Boolean, value: false}
  },
  data: {
    chartImage: '',
    ec: {
      lazyLoad: true, // 延迟加载，与 echarts-all 的 ecAll 隔离
      onInit: (canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
        canvas.setChart(chart);
        return chart;
      }
    }
  },
  lifetimes: {
    ready() { // 替换 attached，统一初始化时机
      this.initEcharts();
    }
  },
  observers: {
    // 监听 trainDate 属性的变化
    'trainDate'(newTrainDate) {
      console.log('组件的 trainDate 已更新为:', newTrainDate);
      // 当 trainDate 变化时，自动重新初始化图表
      if (newTrainDate) { // 确保 newTrainDate 有效
        this.initEcharts();
      }
    }
  },
  methods: {
    async initEcharts() {
      const ecComponent = this.selectComponent('#ecgChart');
      if (!ecComponent) {
        console.error('ecg-chart：未找到 ec-canvas 实例');
        return;
      }
      await ecComponent.init(async (canvas, width, height, dpr) => {
        const res = await studentStateLastApi({
          studentId: store.state.studentId,
          coachId: store.state.coachId,
          factoryNo: store.state.mac,
          trainDate: this.data.trainDate
        });
        console.log(res, 'res')
        const lineXAxis = res.xAxis || [];
        const lineSeries = res.series || [];
        const fixedValues = res.fixedValues || [];
        const myChart = echarts.init(canvas, null, {
          width: this.properties.chartWidth || width,
          height: this.properties.chartHeight || height,
          devicePixelRatio: dpr
        });
        myChart.setOption(this.getChartOption(lineXAxis, lineSeries, fixedValues));
        wx.onWindowResize(() => myChart.resize());
        return myChart;
      });
    },
    getChartOption(lineXAxis, lineSeries, fixedValues) {
      // 原配置逻辑保持不变...
      return {
        grid: { left: '15%', right: '15%', top: '14%', bottom: '5%', containLabel: true },
        xAxis: {
          type: "category",
          data: lineXAxis.map((sec, idx) => idx === 0 ? "" : `${Math.floor(sec / 60)}分钟`),
          axisLabel: { show: true, textStyle: { color: "#666" }, interval: Math.max(1, Math.floor((lineXAxis.length - 1) / 5)) },
          axisLine: { show: false },
          axisTick: { show: false }
        },
        tooltip: { show: false },
        yAxis: [
          { type: "value", name: "bpm", nameTextStyle: { color: "#666" }, splitLine: { show: false }, axisLabel: { show: false }, axisLine: { show: true, lineStyle: { color: "#666" } }, min: 0, max: 250, interval: 50 },
          { type: "value", name: "百分比", nameTextStyle: { color: "#666" }, axisTick: { show: false }, axisLabel: { show: false }, axisLine: { show: false }, splitLine: { show: false }, min: 0, max: 100 }
        ],
        series: [
          {
            data: [50, 100, 150, 200, 250],
            type: "line",
            markLine: {
              silent: true,
              symbol: "none",
              label: { show: true, position: "start", color: "#666", distance: 10, formatter: "{b}" },
              data: [
                { yAxis: 50, name: `${fixedValues[0]||123}`, yAxisIndex: 0 },
                { yAxis: 100, name: `${fixedValues[1]||154}`, yAxisIndex: 0 },
                { yAxis: 150, name: `${fixedValues[2]||174}`, yAxisIndex: 0 },
                { yAxis: 200, name: `${fixedValues[3]||195}`, yAxisIndex: 0 }
              ]
            },
            markArea: {
              tooltip: { show: false },
              silent: true,
              label: { position: ["101%", 0], color: "#666" },
              data: [
                [{ valueDim: "y" }, { yAxis: 50, itemStyle: { color: "#01ffc1" }, name: "60%" }],
                [{ yAxis: 50 }, { yAxis: 100, itemStyle: { color: "#6cff00" }, name: "75%" }],
                [{ yAxis: 100 }, { yAxis: 150, itemStyle: { color: "#f5ff00" }, name: "85%" }],
                [{ yAxis: 150 }, { yAxis: 200, itemStyle: { color: "#ffc208" }, name: "95%" }],
                [{ yAxis: 200 }, { yAxis: 250, itemStyle: { color: "#e70012" }, name: "" }]
              ]
            },
            lineStyle: { width: 0, color: "transparent" },
            symbolSize: 0
          },
          {
            data: lineSeries.map((v) => {
              if (v <= 60) return (v / 60) * 50;
              if (v <= 75) return 50 + ((v - 60) / 15) * 50;
              if (v <= 85) return 100 + ((v - 75) / 10) * 50;
              if (v <= 95) return 150 + ((v - 85) / 10) * 50;
              if (v <= 100) return 200 + ((v - 95) / 5) * 50;
              return 250;
            }),
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 2,
            lineStyle: { normal: { color: "#00f" } }
          }
        ]
      };
    },
    updateChart(trainDate) {
      this.setData({ trainDate });
    }
  }
});